import {
  Directive,
  ElementRef,
  EventEmitter,
  HostListener,
  Input,
  Output,
} from '@angular/core';

@Directive({
  selector: '[clickedOutside]',
  standalone: true,
})
export class ClickOutsideDirective {
  @Input() toggle?: HTMLElement;
  @Output() clickedOutside = new EventEmitter<null>();

  constructor(private host: ElementRef<HTMLElement>) {}

  @HostListener('document:mouseup', ['$event.target'])
  onClick(target: HTMLElement) {
    const isToggle =
      this.toggle && this.toggle.contains(target);
    const isInsideHost =
      this.host.nativeElement.contains(target);

    if (!isToggle && !isInsideHost) {
      this.clickedOutside.emit();
    }
  }
}
